<template>
  <el-container>
    <div class="c1">
      <el-button size="mini" type="primary" icon="el-icon-plus" @click="addmenu"
        >新增</el-button
      >
      <el-button
        :loading="downloadLoading"
        size="mini"
        class="dBtn"
        type="warning"
        icon="el-icon-download"
        @click="download"
        >导出</el-button
      >
      <el-form :inline="true" :model="searchData" class="demo-form-inline s1">
        <el-form-item>
          <el-input
            class="search_inp"
            v-model="searchData.name"
            placeholder="输入'角色名称'查询"
          ></el-input>
        </el-form-item>

        <el-form-item>
          <el-button
            size="mini"
            type="success"
            icon="el-icon-search"
            @click="searchBtn(searchData)"
            >查询</el-button
          >
        </el-form-item>
        <el-form-item>
          <el-button
            size="mini"
            type="warning"
            icon="el-icon-refresh-left"
            @click="searchrestBtn(searchData)"
            >重置</el-button
          >
        </el-form-item>
      </el-form>
    </div>

    <div class="c2">
      <el-row :gutter="20">
        <el-col
          :xs="24"
          :sm="24"
          :md="16"
          :lg="16"
          :xl="17"
          style="margin-bottom: 10px"
        >
          <div class="col1">
            <div class="clearfix1">
              <span>角色列表</span>
            </div>
            <el-table
              :data="tableData"
              style="width: 100%"
              max-height="400"
              highlight-current-row
              size="small"
              align="center"
              @current-change="menuEdit"
            >
              <el-table-column type="index" width="50" label="序号">
              </el-table-column>

              <el-table-column prop="name" label="名称"> </el-table-column>
              <el-table-column prop="isDefault" label="是否是默认角色">
                <template v-slot="prop">
                  <el-switch
                    @change="changeSwitch1(prop.row, prop.row.id)"

                    v-model="prop.row.isDefault"
                    :active-value="true"
                    :inactive-value="false"
                    active-color="#13ce66"
                    inactive-color="#ff4949"
                    active-text="是"
                    inactive-text="否"
                  >
                  </el-switch>
                </template>
              </el-table-column>
              <el-table-column prop="status" label="当前状态">
                <template v-slot="prop">
                  <el-switch
                    @change="changeSwitch(prop.row, prop.row.id)"
                    v-model="prop.row.status"
                    :active-value="1"
                    :inactive-value="0"
                    active-color="#13ce66"
                    inactive-color="#ff4949"
                    active-text="启用"
                    inactive-text="禁用"
                  >
                  </el-switch>
                </template>
              </el-table-column>

              <el-table-column label="操作">
                <template slot-scope="scope">
                  <el-button
                    size="mini"
                    type="primary"
                    icon="el-icon-edit"
                    @click="handleEdit(scope.row)"
                  ></el-button>
                  <el-button
                    type="danger"
                    icon="el-icon-delete"
                    size="mini"
                    @click="handleDelete(scope.row.id)"
                  ></el-button>
                  <!-- <el-button
              size="mini"
              type="info"
              icon="el-icon-refresh-left"
              @click="handleRest(scope.row.id)"
              >重置角色关联</el-button
            > -->
                </template>
              </el-table-column>
            </el-table>
            <div class="pageCon">
              <el-pagination
                @size-change="handleSizeChange"
                @current-change="handleCurrentChange"
                :current-page="this.pageNum.current"
                :page-sizes="[10, 20, 30, 50]"
                :page-size="this.pageNum.size"
                layout="total, sizes, prev, pager, next, jumper"
                :total="this.pageNum.total"
              >
              </el-pagination>
            </div>
          </div>
        </el-col>
        <el-col :xs="24" :sm="24" :md="8" :lg="8" :xl="7">
          <div class="col1">
            <div class="clearfix1">
              <el-tooltip
                class="item"
                effect="dark"
                content="选择指定角色分配菜单"
                placement="top"
              >
                <span>菜单分配</span>
              </el-tooltip>
              <el-button
                size="mini"
                type="primary"
                icon="el-icon-check"
                :disabled="!showButton"
                @click="saveMenu"
                >保存</el-button
              >
            </div>
            <el-tree
              ref="menutree"
              :data="tableData1"
              :default-checked-keys="editDate1.menuIds"
              :props="defaultProps"
              check-strictly
              accordion
              show-checkbox
              node-key="id"
            />
          </div>
        </el-col>
      </el-row>
    </div>

    <!-- 新增菜单对话框 start -->

    <el-dialog
      title="新增角色"
      :visible.sync="addmenuDialogVisible"
      width="30%"
    >
      <el-form
        label-position="left"
        label-width="120px"
        :model="addData"
        :rules="rules"
        ref="ruleForm"
        class="editform"
      >
        <el-form-item label="name" prop="name">
          <el-input v-model="addData.name"></el-input>
        </el-form-item>
        <el-form-item label="是否是默认角色">
          <el-switch
            v-model="addData.isDefault"
            :active-value="true"
            :inactive-value="false"
            active-color="#13ce66"
            inactive-color="#ff4949"
          >
          </el-switch>
        </el-form-item>
        <el-form-item label="是否启用">
          <el-switch
            v-model="addData.status"
            :active-value="1"
            :inactive-value="0"
            active-color="#13ce66"
            inactive-color="#ff4949"
          >
          </el-switch>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="addmenuDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="addmenuDialog">确 定</el-button>
      </span>
    </el-dialog>
    <!-- 新增菜单对话框 end -->

    <!-- 删除 -->
    <el-dialog title="提示" :visible.sync="delmenuDialogVisible" width="30%">
      确认删除吗?
      <span slot="footer" class="dialog-footer">
        <el-button @click="delmenuDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="delmenuDialog">确 定</el-button>
      </span>
    </el-dialog>
    <!-- 修改 -->
    <el-dialog
      title="角色修改"
      :visible.sync="editmenuDialogVisible"
      width="30%"
    >
      <el-form
        label-position="left"
        label-width="110px"
        :model="editDate"
        :rules="rules"
        ref="ruleForm2"
        class="editform"
      >
        <el-form-item label="名称" prop="name">
          <el-input v-model="editDate.name"></el-input>
        </el-form-item>

        <el-form-item label="是否启用">
          <el-switch
            v-model="editDate.status"
            :active-value="1"
            :inactive-value="0"
            active-color="#13ce66"
            inactive-color="#ff4949"
          >
          </el-switch>
        </el-form-item>
        <el-form-item label="是否是默认角色">
          <el-switch
            v-model="editDate.isDefault"
            :active-value="true"
            :inactive-value="false"
            active-color="#13ce66"
            inactive-color="#ff4949"
          >
          </el-switch>
        </el-form-item>
      </el-form>

      <span slot="footer" class="dialog-footer">
        <el-button @click="editmenuDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="editmenuDialog">确 定</el-button>
      </span>
    </el-dialog>
  </el-container>
</template>

<script>
import axios from "../../utils/axios";
import { roleList, newRole,delRole,roleEdite,menuList,menuTree,restRoleMenu } from "../../utils/api";
export default {
  methods: {
    //查询角色列表
    getRoleList(con) {
      roleList({
        current: this.$route.query.current == 1 ? 1 : this.$route.query.current,
        size: this.$route.query.size ? this.$route.query.size : 10,
        name: con,
      }).then((res) => {
        if (res.code == 200) {
          console.log(this.$route.query);
          this.tableData = res.data.records;
          this.pageNum.current = res.data.current;
          this.pageNum.size = res.data.size;
          this.pageNum.total = res.data.total;
        } else {
          this.$message.error(res.message);
        }
      });
      //       axios({
      //         method: "GET",
      //         url: "/sys/role",
      //         params: {
      //     current: this.$route.query.current==1 ? 1 : this.$route.query.current,
      //     size: this.$route.query.size ? this.$route.query.size : 10,
      //     name:con,
      //   }
      // ,
      //       }).then((res) => {
      //         if (res.code == 200) {
      //           console.log(this.$route.query);
      //           this.tableData = res.data.records;
      //           this.pageNum.current = res.data.current;
      //           this.pageNum.size = res.data.size;
      //           this.pageNum.total = res.data.total;

      //         } else {
      //           this.$message.error(res.message);
      //         }
      //       });
    },
    //页码
    handleSizeChange(val) {
      this.$router.replace({
        path: this.$route.path,
        query: {
          current: this.$route.query.current ? this.$route.query.current : 1,
          size: val,
        },
      });

      // this.pageNum.size = val;
      if (this.searchToggle) {
        // this.searchData.current = this.pageNum.current;
        // this.searchData.size = this.pageNum.size;
        this.getRoleList(this.searchData.name);
      } else {
        // this.getRoleList(this.pageNum);
        this.getRoleList();
      }
    },
    handleCurrentChange(val) {
      this.$router.replace({
        path: this.$route.path,
        query: {
          current: val,
          size: this.$route.query.size ? this.$route.query.size : 10,
        },
      });

      // this.pageNum.current = val;

      if (this.searchToggle) {
        // this.searchData.current = this.pageNum.current;
        // this.searchData.size = this.pageNum.size;
        this.getRoleList(this.searchData.name);
      } else {
        // this.getRoleList(this.pageNum);
        this.getRoleList();
      }
    },

    //角色添加

    addmenu() {
      this.addmenuDialogVisible = true;
      this.searchrestBtn();
      console.log(this.sizeCon);
    },
    addmenuDialog() {
      this.$refs.ruleForm.validate((valid) => {
        if (valid) {
          newRole(this.addData).then((res) => {
            if (res.code == 200) {
              this.$message.success("添加成功");
              this.addmenuDialogVisible = false;

              this.getRoleList(this.pageNum);
            } else {
              console.log(res);
              this.$message.error(res.message);
            }
          });

          // axios({
          //   method: "POST",
          //   url: "/sys/role",
          //   data: this.addData,
          // }).then((res) => {
          //   if (res.code == 200) {
          //     this.$message.success("添加成功");
          //     this.addmenuDialogVisible = false;

          //     this.getRoleList(this.pageNum);
          //   } else {
          //     console.log(res);
          //     this.$message.error(res.message);
          //   }
          // });
        } else {
          this.$message.error("内容不完整");
        }
      });
    },

    //查询
    searchBtn(con) {
      this.getRoleList(con.name);
      this.searchToggle = true;
    },
    //导出
    download() {
      this.downloadLoading = true;
    },
    //重置
    searchrestBtn(con) {
      this.searchData.name = "";
      this.getRoleList(con);
      this.searchToggle = false;
    },
    //删除
    handleDelete(con) {
      this.delmenuDialogVisible = true;

      this.delDate = [];
      this.delDate.push(con);
    },
    //角色重置
    handleRest(con) {
      this.delmenuDialogVisible = true;

      this.delDate = [];
      this.delDate.push(con);
    },
    //角色状态,启用
    changeSwitch(con1, con2) {
      if (con1.status == 1) {
        let data = {};
        data.id = con2;
        data.status = con1.status;

        this.$confirm("此操作将启用该角色", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
        })
          .then(() => {
            axios({
              method: "PUT",
              url: "/sys/role",
              data: data,
            }).then((res) => {
              if (res.code == 200) {
                this.$message.success("启用成功！");
                this.getRoleList();
              } else {
                this.$message.error(res.message);
                this.getRoleList();
              }
            });
          })
          .catch(() => {
            this.getRoleList();
          });
      }
      if (con1.status == 0) {
        let data = {};
        data.id = con2;
        data.status = con1.status;

        this.$confirm("此操作将禁用该角色", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
        })
          .then(() => {
            axios({
              method: "PUT",
              url: "/sys/role",
              data: data,
            }).then((res) => {
              if (res.code == 200) {
                this.$message.success("禁用成功！");
                this.getRoleList();
              } else {
                this.$message.error(res.message);
                this.getRoleList();
              }
            });
          })
          .catch(() => {
            this.getRoleList();
          });
      }
    },
    //角色状态,默认角色
    changeSwitch1(con1, con2) {
      if (con1.status == 1) {
        let data = {};
        data.id = con2;
        data.status = con1.isDefault;

        this.$confirm("此操作将改变角色默认状态", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
        })
          .then(() => {
            axios({
              method: "PUT",
              url: "/sys/role",
              data: data,
            }).then((res) => {
              if (res.code == 200) {
                this.$message.success("操作成功！");
                this.getRoleList();
              } else {
                this.$message.error(res.message);
                this.getRoleList();
              }
            });
          })
          .catch(() => {
            this.getRoleList();
          });
      }
      if (con1.status == 0) {
        let data = {};
        data.id = con2;
        data.status = con1.isDefault;

        this.$confirm("此操作将改变角色默认状态", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
        })
          .then(() => {
            axios({
              method: "PUT",
              url: "/sys/role",
              data: data,
            }).then((res) => {
              if (res.code == 200) {
                this.$message.success("操作成功！");
                this.getRoleList();
              } else {
                this.$message.error(res.message);
                this.getRoleList();
              }
            });
          })
          .catch(() => {
            this.getRoleList();
          });
      }
    },
    //删除对话框
    delmenuDialog() {
      delRole(this.delDate).then((res) => {
        if (res.code == 200) {
          this.$message.success("删除成功");
          this.delmenuDialogVisible = false;
          this.getRoleList(this.pageNum);
        } else {
          this.$message.error(res.message);
        }
      });
      // axios({
      //   method: "delete",
      //   url: "/sys/role",

      //   data: JSON.stringify(this.delDate),
      //   // headers: {
      //   //   "Content-Type": "application/json;charset=UTF-8",
      //   // },
      // }).then((res) => {
      //   if (res.code == 200) {
      //     this.$message.success("删除成功");
      //     this.delmenuDialogVisible = false;
      //     this.getRoleList(this.pageNum);
      //   } else {
      //     this.$message.error(res.message);
      //   }
      // });
    },

    //右侧菜单树-总
    getMenu() {
      let data = {};
      data.isAll = true;
      menuTree(data).then((res) => {
        if (res.code == 200) {
          this.tableData1 = res.data;
        } else {
          this.$message.error(res.message);
        }
      });
      // axios({
      //   method: "GET",
      //   url: "/sys/menu/tree",
      //   params: data,
      // }).then((res) => {
      //   if (res.code == 200) {
      //     this.tableData1 = res.data;
      //   } else {
      //     this.$message.error(res.message);
      //   }
      // });
    },

    //修改
    handleEdit(con) {
      this.editmenuDialogVisible = true;

      this.editDate.status = con.status;
      this.editDate.name = con.name;
      this.editDate.id = con.id;
      this.editDate1.roleId = con.id;
    },
    editmenuDialog() {
      this.$refs.ruleForm2.validate((valid) => {
        if (valid) {
          roleEdite(this.editDate).then((res) => {
            if (res.code == 200) {
              console.log(222);
              this.$message.success("修改成功");
              this.editmenuDialogVisible = false;
              this.getRoleList(this.pageNum);
            } else {
              console.log(res);
              this.$message.error(res.message);
            }
          });
          // axios({
          //   method: "PUT",
          //   url: "/sys/role",
          //   data: this.editDate,
          // }).then((res) => {
          //   if (res.code == 200) {
          //     this.$message.success("添加成功");
          //     this.editmenuDialogVisible = false;
          //     this.getRoleList(this.pageNum);
          //   } else {
          //     console.log(res);
          //     this.$message.error(res.message);
          //   }
          // });
        } else {
          this.$message.error("内容不完整");
        }
      });
    },

 
    //获取角色菜单
    getRoleMenus(con) {
      let data = {};
      data.size = -1;
      data.roleId = con;
      menuList(data).then((res) => {
        if (res.code == 200) {
          // this.tableData2= res.data.records;
          // console.log(this.tableData2);
          let roleMenu = res.data.records;
          console.log(res);
          let checkedMenuIds = [];
          for (let i = 0; i < roleMenu.length; i++) {
            if (roleMenu != null && roleMenu.length > 0) {
              checkedMenuIds.push(roleMenu[i].id);
            }
          }
          this.$refs.menutree.setCheckedKeys(checkedMenuIds);
        } else {
          this.$message.error(res.message);
        }
      });
    
    },
    //右侧菜单树
    menuEdit(val) {
      if (val) {
        this.$refs.menutree.setCheckedKeys([]);
        //获取用户当前菜单
        this.getRoleMenus(val.id);

        // const that = this
        // // 清空菜单的选中
        // this.$refs.menu.setCheckedKeys([])
        // // 保存当前的角色id
        this.currentId = val.id;
        this.editDate1.roleId = val.id;

        // // 点击后显示按钮
        this.showButton = true;
        // // 初始化
        this.editDate1.menuIds = [];
        // // 菜单数据需要特殊处理

        //  this.tableData2.forEach(function(data, index) {
        //     that.editDate1.menuIds.push(data.id)
        //       let da =[]
        //       da.push(index)
        //   })
      }
    },
    //保存菜单修改

    saveMenu() {
      const that = this;
      that.editDate1.menuIds = [];
      // this.menuLoading = true

      // const role = { id: this.currentId, menus: [] }
      // 得到半选的父节点数据，保存起来
      this.$refs.menutree.getHalfCheckedNodes().forEach(function (data, index) {
        // const menu = { id: data.id }
        // role.menus.push(menu)
        that.editDate1.menuIds.push(data);
        console.log(index);
      });
      // 得到已选中的 key 值
      this.$refs.menutree.getCheckedKeys().forEach(function (data, index) {
        // const menu = { id: data }
        // role.menus.push(menu)
        that.editDate1.menuIds.push(data);
        console.log(index);
      });

      this.$confirm("此操作将重置该角色菜单列表, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          restRoleMenu(this.editDate1).then((res) => {
            if (res.code == 200) {
              this.$message.success("菜单配置成功");
              this.innerVisible = false;
            } else {
              this.$message.error(res.message);
            }
            this.$router.go(0);
          });
          // axios({
          //   method: "POST",
          //   url: "/sys/menu/reset",
          //   data: this.editDate1,
          // }).then((res) => {
          //   if (res.code == 200) {
          //     this.$message.success("菜单配置成功");
          //     this.innerVisible = false;
          //   } else {
          //     this.$message.error(res.message);
          //   }
          //   this.$router.go(0);
          // });
        })
        .catch(() => {
          this.$message({
            type: "warning",
            message: "已取消",
          });
          this.$router.go(0);
        });
    },
  },
  data() {
    return {
      pageNum: {
        current: 1,
        size: 10,
        total: 0,
      },
   
      defaultProps: {
        children: "children",
        label: "name",
      },
      showButton: false,
      currentId: "",
      addmenuDialogVisible: false,
      delmenuDialogVisible: false,
      editmenuDialogVisible: false,
      innerVisible: false,
      searchToggle: false,
      downloadLoading: false,
      delDate: [],
      searchData: {
        name: "",
        id: "",
        status: "",
      },
      editDate: {
        id: "",
        status: "",
        name: "",
        isDefault: "",
      },
      sizeCon: 1,
      editDate1: {
        menuIds: [],
        roleId: "",
      },
      tableData: [],
      tableData1: [],
      tableData2: [],
      addData: {
        status: 1,
        isDefault: true,
      },
      rules: {
        name: [{ required: true, message: "必填", trigger: "blur" }],
        path: [{ required: true, message: "必填", trigger: "blur" }],
        status: [{ required: true, message: "必填", trigger: "blur" }],
      },
      rules3: {
        menuIds: [{ required: true, message: "必填", trigger: "blur" }],
      },
    };
  },
  watch: {
    "pageNum.total": function () {
      // if(this.pageNum.total==0){
      //   this.$route.query.current =1
      //   this.$route.query.size =10
      //   this.getRoleList()

      // }
      if (
        this.pageNum.total == (this.pageNum.current - 1) * this.pageNum.size &&
        this.pageNum.total != 0
      ) {
        // this.pagination.current_page-=1;
        // this.getStuList(this.pages)
        console.log("更新成果");
        // this.pageNum.current -= 1;
        this.$route.query.current -= 1;

        if (this.searchToggle) {
          let con = this.searchData;
          // con.campusId = localStorage.getItem("userId");
          // con.currentPage = this.pagination.currentPage;
          // con.perPageSize = this.pagination.perPageSize;
          this.getRoleList(con.name);


        } else {
          this.getRoleList();
        }
      }
      let a1 = Math.ceil(this.pageNum.total / this.pageNum.size);
      if (a1 < this.pageNum.current) {
        // this.pagination.currentPage = a1;
        this.$route.query.current = a1;
        if (this.searchToggle) {
          let con = this.searchData;
          // con.campusId = localStorage.getItem("userId");
          // con.currentPage = this.pagination.currentPage;
          // con.perPageSize = this.pagination.perPageSize;
          this.getRoleList(con.name);
        } else {
          this.getRoleList();
        }
      }
    },
  },
  created() {
    this.getRoleList();
    this.getMenu();
    this.searchToggle = false;
  },
};
</script>

<style lang="less" scoped>
.el-container {
  display: flex;
  justify-content: start;
  flex-direction: column;
  align-items: center;
}
.c2 {
  width: 100%;
}
.s1 {
  height: 0;
  margin-top: 2.5rem;
  display: flex;
  align-items: center;
}
.el-footer {
  align-self: start;
  margin-top: 1.5rem;
}
.c1 {
  display: flex;
  justify-content: start;
  margin-bottom: 1.5rem;
  width: 100%;
  .dBtn {
    margin-right: 1rem;
  }
}
.el-input /deep/.el-input__inner {
  height: 3.05rem;
}
.el-dialog {
  display: flex;
  justify-content: flex-start;
}
.pageCon {
  display: flex;
  justify-content: start;
  align-items: center;
  margin-top: 1.3rem;

  padding-top: 2rem;
}
.btns {
  display: flex;
  justify-content: space-between;
}
.editform {
  display: flex;
  justify-content: start;
  flex-wrap: wrap;
  text-align: left;

  .el-input /deep/.el-input__inner {
    height: 3.05rem;
    font-size: 12px !important;
  }
}
.el-input /deep/.el-input__inner {
  height: 3.05rem;
  font-size: 12px !important;
}
.editform /deep/ .el-form-item {
  display: inline-block;
  margin-left: 1rem;
}
.editform /deep/ .el-form-item__content {
  height: 3.05rem;
}
.clearfix1 {
  font-weight: 700;
  color: #303133;
  font-size: 15px;
  display: flex;
  justify-content: space-between;

  padding: 18px 20px;
  border-bottom: 1px solid #e6ebf5;
  -webkit-box-sizing: border-box;
  box-sizing: border-box;
  span {
    display: block;
  }
}
.col1 {
  border: 1px solid #e6ebf5;
  padding-bottom: 2rem;
}

.el-table /deep/ {
  font-size: 12px;
  padding: 2rem 0 0 2rem;
  overflow: visible;
}
.el-switch /deep/ .el-switch__label * {
  font-size: 12px;
}
.el-table /deep/ thead {
  font-size: 12.5px;
  color: #909399;
  font-weight: 700;
}
.el-tree {
  padding: 20px;
}
.el-table /deep/ .el-table--small td {
  padding: 3px 0 !important;
}
.el-table::before {
  z-index: inherit;
  visibility: hidden;
}
</style>